package com.zzt.zt_cropimageview;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.zzt.zt_cropimageview.loader.GlideImageLoader;

import java.io.File;
import java.util.ArrayList;


public class ImageCropActivity extends AppCompatActivity implements View.OnClickListener,
        TempImageViewV1.OnBitmapSaveCompleteListener {
    private static final String TAG = "TempImageView act";

    public static void start(Activity context, int code) {
        Intent starter = new Intent(context, ImageCropActivity.class);
        context.startActivityForResult(starter, code);
    }

    private GlideCropImageViewV1 mCropImageView;
    private boolean mIsSaveRectangle;
    private int mOutputX;
    private int mOutputY;
    private ArrayList<GLImage> mGLImages;
    private ImagePicker imagePicker;
    private TextView btn_ok;
    private TextView tv_des;
    private FrameLayout fl_parent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nim_activity_image_crop);

        imagePicker = ImagePicker.getInstance();

        //初始化View
        findViewById(R.id.btn_back).setOnClickListener(this);
        btn_ok = findViewById(R.id.btn_ok);
        btn_ok.setText(getString(R.string.complete));
        btn_ok.setOnClickListener(this);
        tv_des = findViewById(R.id.tv_des);
        tv_des.setText(getString(R.string.photo_crop));
        mCropImageView = findViewById(R.id.cv_crop_image);
        fl_parent = findViewById(R.id.fl_parent);

        TempTextMessageObj messageObj = new TempTextMessageObj();
        messageObj.setIssue("no.1111111");
        messageObj.setAmount("1000");
        messageObj.setCurrencySymbol("$");
        messageObj.setCreditDes("credit");
        messageObj.setName("name");
        messageObj.setCountryName("国家");
        mCropImageView.setMessageObj(messageObj);

//        mCropImageView.setFocusStyle(imagePicker.getStyle());
//        mCropImageView.setFocusWidth(imagePicker.getFocusWidth());
//        mCropImageView.setFocusHeight(imagePicker.getFocusHeight());

        //获取需要的参数
        mOutputX = imagePicker.getOutPutX();
        mOutputY = imagePicker.getOutPutY();
        mIsSaveRectangle = imagePicker.isSaveRectangle();
        mGLImages = imagePicker.getSelectedImages();
        String imagePath = mGLImages.get(0).getPath();


        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        final View loadingView = findViewById(R.id.pb_loading);
        loadingView.setVisibility(View.GONE);

//        Glide.with(this).asBitmap().load(imagePath).addListener(new RequestListener<Bitmap>() {
//            @Override
//            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
//                Log.d(TAG, "图片加载 失败 onLoadFailed");
//                return false;
//            }
//
//            @Override
//            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
//                mCropImageView.setImageBitmap(resource);
//                Log.d(TAG, "图片加载 成功 onResourceReady resource：" + resource);
//                return false;
//            }
//        }).preload();


        btn_ok.setEnabled(false);

        ImagePicker.getInstance().getImageLoader().displayImage(this, imagePath, mCropImageView,
                displayMetrics.widthPixels, displayMetrics.heightPixels, new GlideImageLoader.LoadListener() {
                    @Override
                    public void onLoadSuccess() {
                        loadingView.setVisibility(View.GONE);
                        btn_ok.setEnabled(true);
                    }

                    @Override
                    public void onLoadFailed() {

                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_back) {
            setResult(RESULT_CANCELED);
            finish();
        } else if (id == R.id.btn_ok) {
            boolean ret = mCropImageView.saveBitmapToFile(imagePicker.getCropCacheFolder(this), 1080, 1080);
            if (!ret) {
                Toast.makeText(this, "裁剪失败，换一张试试", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onBitmapSaveSuccess(File file) {
        //裁剪后替换掉返回数据的内容，但是不要改变全局中的选中数据
        GLImage glImage = mGLImages.remove(0);
        GLImage newItem = GLImage.Builder.newBuilder(glImage).setPath(file.getAbsolutePath()).build();
        mGLImages.add(0, newItem);

        Intent intent = new Intent();
//        intent.putExtra(Constants.EXTRA_RESULT_ITEMS, mGLImages);

        intent.putExtra(Extras.EXTRA_FILE_PATH, mGLImages.get(0).getPath());
        setResult(RESULT_OK, intent);   //单选不需要裁剪，返回数据
        finish();
    }

    @Override
    public void onBitmapSaveError(File file) {

    }


}
